<template>
  <div class="TaskDialog">
    <!-- 弹出框开始 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialog.model === 'info' ? '工单详情' : '新增工单'"
      :visible="dialog.visible"
      width="630px"
      :before-close="closeFn"
    >
      <span v-loading="loading" element-loading-background="rgba(0, 0, 0, 0)" :element-loading-text="dialog.model === 'info' ? '刷新數據中' : '正在上傳'">
        <!-- 工单新建開始 -->
        <template v-if="dialog.model === 'new'">
          <el-form ref="newTaskForm" :model="newTaskForm" :rules="newTaskFormRules" label-width="140px">
            <el-form-item label="设备编号：" prop="innerCode">
              <el-input v-model.trim="newTaskForm.innerCode"
              placeholder="请输入"
              @input="newTaskUser"
              maxlength="15"
              show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="工单类型：" prop="productType">
              <el-select v-model="newTaskForm.productType" placeholder="请选择">
                <el-option
                v-for="item in taskType"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运营人员：" prop="assignorId">
              <el-select v-model="newTaskForm.assignorId" placeholder="请选择">
                <el-option
                v-for="item in operatorList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注：" prop="desc">
              <el-input type="textarea"
              v-model="newTaskForm.desc"
              placeholder="请输入备注（不超过40字）"
              maxlength="40"
              show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
        </template>
        <!-- 新建工单结束 -->
        <template v-if="dialog.model === 'info'">
          <div class="showShowNeed">
              <div
                class="header"
                v-if="taskInfo.taskStatusTypeEntity?.statusId === 1"
              >
                <div class="icon">
                  <img src="@/assets/Task1-0.png" />
                </div>
                <div class="title">待办</div>
                <div class="pic">
                  <img src="@/assets/Task1-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taskInfo.taskStatusTypeEntity?.statusId === 2"
              >
                <div class="icon">
                  <img src="@/assets/Task1-0.png" />
                </div>
                <div class="title">进行</div>
                <div class="pic">
                  <img src="@/assets/Task1-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taskInfo.taskStatusTypeEntity?.statusId === 3"
              >
                <div class="icon">
                  <img src="@/assets/Task3-0.png" />
                </div>
                <div class="title">取消</div>
                <div class="pic">
                  <img src="@/assets/Task3-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taskInfo.taskStatusTypeEntity?.statusId === 4"
              >
                <div class="icon">
                  <img src="@/assets/Task4-0.png" />
                </div>
                <div class="title">完成</div>
                <div class="pic">
                  <img src="@/assets/Task4-1.png" />
                </div>
              </div>
              <div class="info">
                <div class="col">
                  <div class="row">
                    <div class="title">设备编号：</div>
                    <div class="col">{{ taskInfo.innerCode }}</div>
                  </div>
                  <div class="row">
                    <div class="title">创建日期：</div>
                    <div class="col">
                      {{ taskInfo.createTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taskInfo.taskStatusTypeEntity?.statusId === 4"
                  >
                    <div class="title">完成日期：</div>
                    <div class="col">
                      {{ taskInfo.updateTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taskInfo.taskStatusTypeEntity?.statusId === 3"
                  >
                    <div class="title">取消日期：</div>
                    <div class="col">
                      {{ taskInfo.updateTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div class="row">
                    <div class="title">运营人员：</div>
                    <div class="col">{{ taskInfo.userName }}</div>
                  </div>
                  <div class="row">
                    <div class="title">工单类型：</div>
                    <div class="col">{{ taskInfo.taskType?.typeName }}</div>
                  </div>
                  <div class="row">
                    <div class="title">工单方式：</div>
                    <div class="col">
                      {{ taskInfo.createType ? "手动" : "自动" }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taskInfo.taskStatusTypeEntity?.statusId !== 3"
                  >
                    <div class="title">备注：</div>
                    <div class="col">{{ taskInfo.desc }}</div>
                  </div>
                  <div
                    class="row"
                    v-if="taskInfo.taskStatusTypeEntity?.statusId === 3"
                  >
                    <div class="title">取消原因：</div>
                    <div class="col">{{ taskInfo.desc }}</div>
                  </div>
                  <div
                    class="row"
                  >
                    <div class="title">定位：</div>
                    <div class="col" style="width: 137px"><i class="el-icon-position" />&nbsp;&nbsp;{{ taskInfo.addr?.split('-')[taskInfo.addr?.split('-').length - 1 ] }}</div>
                  </div>
                </div>
              </div>
            </div>
        </template>
      </span>
      <span slot="footer" class="dialog-footer">
        <!-- 新建工单开始 -->
        <template  v-if="dialog.model === 'new'">
          <el-button @click="closeFn" size="medium">取消</el-button>
          <el-button type="primary" @click="pushTask" size="medium">确定</el-button>
        </template>
        <!-- 新建工单结束 -->
        <!-- 取消工单開始 -->
          <el-button
            size="medium"
            @click="closeTask(taskInfo.taskId)"
            v-if="taskInfo.taskStatusTypeEntity?.statusId === 1 && !newTaskForm?.innerCode"
            >取消工单</el-button
          >
        <!-- 取消工单結束 -->
        <!-- 重新創建開始 -->
          <el-button
            size="medium"
            @click="reNewTask"
            v-if="taskInfo.taskStatusTypeEntity?.statusId === 3 && !newTaskForm?.innerCode"
            >重新创建</el-button
          >
        <!-- 重新創建結束 -->
      </span>
    </el-dialog>
    <!-- 弹出框结束 -->
  </div>
</template>

<script>
import {
  getTaskType,
  newTaskUser,
  postTask,
  getTaskInof,
  taskCancel
} from '@/api/taskAPIs'
export default {
  props: {
    dialog: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      loading: false, // 載入狀態
      // 工单分类表
      taskType: [],
      newTaskForm: {
        assignorId: '', // 运营人员
        createType: 1, // 创建类型 默认1
        desc: '', // 工单描述
        details: [],
        innerCode: '', // 设备编号
        productType: '', // 工单类型
        userId: this.$store.state.user.userId // 营运人员ID
      },
      // 表單校驗
      newTaskFormRules: {
        innerCode: [{ required: true, message: '设备编号不能为空' }],
        productType: [{ required: true, message: '工单类型不能为空' }],
        assignorId: [{ required: true, message: '运营人员不能为空' }],
        desc: [{ required: true, message: '备注不能为空' }]
      },
      timeOut: null, // 防抖使用
      operatorList: [], // 運營人員列表
      taskInfo: [] // 儲存工單訊息
    }
  },
  async created () {
    // 获取工单分类表
    const { data: taskType } = await getTaskType()
    this.taskType = taskType.filter((item) => item.typeName !== '补货工单')
  },
  methods: {
    // 关闭弹出框
    async closeFn () {
      // 重置状态
      this.$emit('update:dialog', {
        visible: false, // 是否形式
        model: '', // 模式
        taskID: 0 // 工单ID
      })
      // 重置表单
      this.newTaskForm = {
        assignorId: '', // 运营人员
        createType: 1, // 创建类型 默认1
        desc: '', // 工单描述
        details: [],
        innerCode: '', // 设备编号
        productType: '', // 工单类型
        userId: this.$store.state.user.userId // 营运人员ID
      }
      await this.$refs.newTaskForm.resetFields()
      // 重置工单详情
      this.taskInfo = []
      // 重置运营人员
      this.operatorList = []
    },
    // 获取工单运营人员
    newTaskUser (val) {
      if (val !== ' ' && val.length) {
        if (this.timeOut) clearTimeout(this.timeOut)
        this.timeOut = setTimeout(async () => {
          const { data } = await newTaskUser(val)
          this.operatorList = data
        }, 500)
      }
    },
    // 发送工单
    async pushTask () {
      console.log(123)
      try {
        await this.$refs.newTaskForm.validate()
        await postTask(this.newTaskForm)
        this.$message.success('提交成功')
      } catch (e) {
        console.log(e)
      } finally {
        this.closeFn()
        this.$parent.searchTaskList(true)
      }
    },
    // 獲取工單詳情
    async getTaskInof (taskID) {
      try {
        this.loading = true
        const { data } = await getTaskInof(taskID)
        this.taskInfo = data
      } catch (error) {
        console.log(error)
        this.closeFn()
      } finally {
        this.loading = false
      }
    },
    // 取消工单
    closeTask (taskID) {
      this.$confirm(
        '<i class="el-icon-warning" style="color: #ff665f;"></i>&nbsp;&nbsp;取消工单后，将不能恢复，是否确认取消？',
        {
          center: true,
          dangerouslyUseHTMLString: true
        }
      )
        .then(async () => {
          await taskCancel(taskID)
          this.closeFn()
          this.$parent.searchTaskList(true)
        })
        .catch(() => {
          // 留着不给报错
        })
    },
    // 重新創建工單
    reNewTask () {
      // 拉取运营人员
      this.newTaskUser(this.taskInfo.innerCode)
      // 填入数据
      this.newTaskForm.innerCode = this.taskInfo.innerCode
      this.newTaskForm.productType = this.taskInfo.productTypeId
      this.newTaskForm.assignorId = this.taskInfo.assignorId
      this.newTaskForm.desc = this.taskInfo.desc
      // 切换显示模式
      this.$emit('update:dialog', {
        visible: true, // 是否显示
        model: 'new', // 模式
        taskID: 0 // 工单ID
      })
    }
  },
  watch: {
    dialog: {
      handler (newVal) {
        console.log(newVal)
        // 如果是顯示表單訊息就拉取表單
        if (newVal.model === 'info' && newVal.taskID !== 0) {
          this.getTaskInof(newVal.taskID)
        }
      },
      deep: true // 深入監聽
    }
  }
}
</script>

<style lang="scss" scoped>
.TaskDialog {
  .el-form {
    padding-right: 30px;
    .el-select {
      width: 100%;
    }
  }
}
.showShowNeed {
  .header {
    display: flex;
    align-items: center;
    height: 54px;
    margin-bottom: 25px;
    background: #f8f8f8;
    .icon {
      img {
        width: 26px;
        height: 26px;
        margin-left: 22px;
      }
    }
    .title {
      flex: 1;
      margin-left: 16px;
      color: #242525;
    }
    .pic {
      margin-right: 76px;
      margin-bottom: 7px;
    }
  }
  .info {
    color: #606266;
    display: flex;
    font-size: 13px;
    .row {
      height: 36px;
      flex: 50%;
      display: flex;
      align-items: center;
    }
    .col {
      display: flex;
      flex-wrap: wrap;
    }
    .title {
      width: 120px !important;
      text-align: end;
      padding-right: 12px;
    }
  }
}
</style>
